package com.hugh.dubbo.service.consumer.service.impl;

import com.google.common.base.Stopwatch;
import com.hugh.dubbo.api.HelloService;
import com.hugh.dubbo.service.consumer.service.TestTwoService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Hugh
 * @Date: 2020/7/4
 */
@Service
public class TestTwoServiceImpl implements TestTwoService {

    @Reference
    private HelloService helloService;

    /**
     * 不断调用Dubbo服务的3个方法（建议利用线程池进行并行调用，确保在1分钟内可以被调用2000次以上）
     * @param paraCount
     * @return
     */
    @Override
    public Object getTestTwo(Integer paraCount) {
        if(Objects.isNull(paraCount)){
            paraCount = 1000;
        }
        Integer paraCountMax = paraCount + 100;
        //调用总次数
        int count = ThreadLocalRandom.current().nextInt(paraCount, paraCountMax);
        Stopwatch started = Stopwatch.createStarted();
        for(int i=0;i<count;i++){
            //每一次从三个接口中随机选一个
            int interfaceId = ThreadLocalRandom.current().nextInt(3);
            doCall(interfaceId, i, "次数是" + paraCount);
        }
        return "当前请求共发生了" + count + "次调用" + ", " +  "共花费了" +started.elapsed(TimeUnit.SECONDS) +"秒 \n" +
                "(请求次数介于" + paraCount +"和" + paraCountMax +"之间)";
    }

    private void doCall(int interfaceId, int i, String name) {
        if(1 == interfaceId){
            helloService.sayHello2You(name + i);
        } else if(2 == interfaceId){
            helloService.sayHello2Me(name + i);
        } else {
            helloService.sayHello2All(name + i);
        }
    }
}
